;

(function() {

	//  构造函数
	function View(elem, notes, rightWrap, leftWrap) {
		this.rightWrap = rightWrap;
		this.leftWrap = leftWrap;
		this.args = typeof elem === 'object' ? elem : document.getElementById(elem);
		this.notes = notes === undefined ? [] : notes;
		this.init();
	}

	//  原型
	View.prototype = {
		constructor: View,
		init: function() {
			var self = this;
			self.setSite();
			self.bindClick(document.body, 'click', 'mark', function(e) {
				var target = e.target;
				if(this.style.height) {
					this.style.height = '';
					self.resetTop(this, 'close');
					return;
				} else {
					this.style.height = this.scrollHeight + 'px';
					self.resetTop(this, 'open');
				}
			});
		},
		//      设定初始高度

		setSite: function() {
			for(let i = 0; i < this.args.length; i++) {
				//               默认新建的批注距离顶部的高度
				var swdTop = 0;
				var addMark = '';
				//              计算当前批注的高度是否被覆盖,如果被覆盖,进行处理
				if(i > 0) {
					if(this.args[i].offsetTop - this.args[i - 1].offsetTop > $('.note-' + (i - 1)).height()) {
						swdTop = this.args[i].offsetTop - 2 + 'px';
					} else {
						swdTop = this.args[i - 1].offsetTop + $('.note-' + (i - 1)).height() - 2 + 'px';
					}
				} else {
					swdTop = this.args[i].offsetTop - 2 + 'px';
				}
				if(this.notes.length > 0) {
					addMark = '<mark class="note-' + i + '" style="top:' + swdTop + '">' + this.args[i].innerHTML + '：' + this.notes[i] + '</mark>';
				} else {
					addMark = '';
				}
				
				//                 将得到的新标签动态添加到容器中
				if(this.args[i].classList.length > 1 && this.args[i].classList[1] === 'nleft' && this.leftWrap !== undefined) {
					this.leftWrap.append(addMark);
				} else {
					this.rightWrap.append(addMark);
				}
			}
		},
		
		//      重新设置元素高度
		resetTop: function(elem, type) {
			let index = parseInt(elem.className.substr(elem.className.indexOf('-') + 1));
			for(; index < this.args.length - 1; index++) {
				var swdNewTop = 0;
				var addTop = [];
				if(this.args[index + 1].offsetTop - this.args[index].offsetTop > $('.' + elem.className).height()) {
					console.log('我们不需要执行任何东西了')
					return
				} else {
					if(type === 'open') {
						swdNewTop = this.args[index].offsetTop + $('.' + elem.className).height() + 8 + 'px';
						addTop[index + 1] = swdNewTop;
					} else {
						swdNewTop = this.args[index].offsetTop + $('.' + elem.className).height() + 'px';
					}
					$('.note-' + (index + 1)).attr('style', 'top:' + swdNewTop);
					return
				}
			}
		},
		
		//      绑定元素点击事件
		bindClick: function(elem, type, selector, fn) {
			if(fn === null) {
				fn = selector;
				selector = null;
			}
			elem.addEventListener(type, function(e) {
				var target = e.target;
				if(selector) {
					target = e.target;
					if(target.matches(selector)) {
						fn.call(target, e);
					}
				} else {
					fn(e);
				}
			})
		}
	}
	//  对外公开方法
	window.View = View;

})();